package config

import (
	"bytes"
	"errors"
	"io/ioutil"
	"strings"

	"gitee.com/les49/esgo/encoding/json"
	"gitee.com/les49/esgo/encoding/toml"
	"gitee.com/les49/esgo/os/file"
)

const (
	DefaultConfigFile = "config.toml" // The default configuration file name.
	DefaultConfigPath = "./config"
)

var configData map[string]interface{}

func getPath(name string) string {
	return DefaultConfigPath + "/" + name
}

func LoadFile(name string) error {
	var err error
	var fileContent []byte
	var result map[string]interface{}
	fileName := DefaultConfigFile
	if name != "" {
		fileName = name
	}

	path := getPath(fileName)
	fileContent, err = ioutil.ReadFile(path)
	if err != nil {
		return err
	}

	// g.Cfg().SetFileName(name)
	extName := file.ExtName(name)
	switch extName {
	case ".toml", "toml":
		if fileContent, err = toml.ToJson(fileContent); err != nil {
			return err
		}
	default:
		return errors.New("not support")
	}

	decoder := json.NewDecoder(bytes.NewReader(fileContent))
	if err := decoder.Decode(&result); err != nil {
		return err
	}

	// switch result.(type) {
	// case string, []byte:
	// 	return errors.New("json decoder error")
	// }

	// fmt.Println(result)
	// fmt.Println(result.(type))
	configData = result

	return nil
}

func GetString(key string) string {
	var m map[string]interface{}
	var v interface{}

	if configData == nil {
		return ""
	}

	if key == "" {
		return ""
	}

	m = configData
	keys := strings.Split(key, ".")
	for i, k := range keys {
		switch m[k].(type) {
		case map[string]interface{}:
			v = m[k]
			m = v.(map[string]interface{})
		case string:
			v = m[k]
		default:
			if i != (len(keys) - 1) {
				return ""
			}
		}
	}

	str, ok := v.(string)
	if !ok {
		return ""
	}

	return str
}

func GetMap(key string) map[string]interface{} {
	return nil
}
